/**
 * 获取设备的通道列表
 * @param {Object} filterDevice - 过滤条件对象，包含pid、vid、productName、usagePage
 * @returns {Promise<Array|Object>} 如果有过滤条件则返回匹配的HID设备对象，否则返回所有HID设备对象列表
 */
export async function getDeviceChannels(filterDevice = null) {
  try {
    // 检查浏览器是否支持WebHID API
    if (!navigator.hid) {
      throw new Error('当前浏览器不支持WebHID API')
    }

    // 获取已连接的设备
    const devices = await navigator.hid.getDevices()
    if (devices.length === 0) {
      console.warn('没有找到已连接的HID设备')
      return []
    }

    // 如果有过滤条件，查找匹配的设备
    if (filterDevice) {
      const matchedDevice = devices.find(device => {
        const pid = device.productId ? `0x${device.productId.toString(16).padStart(4, '0').toUpperCase()}` : 'N/A'
        const vid = device.vendorId ? `0x${device.vendorId.toString(16).padStart(4, '0').toUpperCase()}` : 'N/A'
        const productName = device.productName || '未知设备'
        let usagePage = 'N/A'
        let usage = 'N/A'
        // 获取第一个集合的UsagePage信息
        if (device.collections && device.collections.length > 0) {
          const collection = device.collections[0]
          usagePage = collection.usagePage ? `0x${collection.usagePage.toString(16).padStart(4, '0').toUpperCase()}` : 'N/A'
          usage = `0x${collection.usage.toString(16).padStart(4, '0').toUpperCase()}`
        }
        
        const pidMatch = !filterDevice.pid || pid === filterDevice.pid
        const vidMatch = !filterDevice.vid || vid === filterDevice.vid
        const productNameMatch = !filterDevice.productName || productName === filterDevice.productName
        const usagePageMatch = !filterDevice.usagePage || usagePage === filterDevice.usagePage
        const usageMatch =  usage === filterDevice.usage
        return pidMatch && vidMatch && productNameMatch && usagePageMatch && usageMatch
      })
      
      return matchedDevice || null
    }

    // 返回原始的HID设备对象列表
    return devices
  } catch (error) {
    console.error('获取设备通道列表失败:', error)
    throw error
  }
}


/**
 * 传入 HID device 对象，返回格式化的设备信息
 * @param {Object} hidDevice - 原始的 HID device 对象
 * @returns {Object} 格式化的设备信息对象 {pid, vid, productName, usagePage}
 */
export function formatHidDevice(hidDevice) {
  if (!hidDevice) {
    return null
  }

  const deviceInfo = {
    pid: hidDevice.productId ? `0x${hidDevice.productId.toString(16).padStart(4, '0').toUpperCase()}` : 'N/A',
    vid: hidDevice.vendorId ? `0x${hidDevice.vendorId.toString(16).padStart(4, '0').toUpperCase()}` : 'N/A',
    productName: hidDevice.productName || '未知设备',
    usagePage: 'N/A',
    usage: 'N/A'
  }

  // 获取第一个集合的UsagePage信息
  if (hidDevice.collections && hidDevice.collections.length > 0) {
    const collection = hidDevice.collections[0]
    deviceInfo.usagePage = collection.usagePage ? `0x${collection.usagePage.toString(16).padStart(4, '0').toUpperCase()}` : 'N/A'
    deviceInfo.usage =  `0x${collection.usage.toString(16).padStart(4, '0').toUpperCase()}` 
  }

  return deviceInfo
}

/**
 * 解析DataView中8F后一位的32-bit指针
 * @param {DataView} dataView - 接收到的DataView数据
 * @returns {number|null} 32-bit指针值，如果未找到返回null
 */
function parse8FPointer(dataView) {
    try {
        // 遍历DataView查找8F标记
        for (let i = 0; i < dataView.byteLength - 4; i++) {
            const byte = dataView.getUint8(i);
            if (byte === 0x8F) {
                // 找到8F，读取后一位开始的32-bit指针（小端序）
                const pointer = dataView.getUint32(i + 1, true);
                console.log(`在位置 ${i} 找到8F标记，指针位置: ${i + 1}-${i + 4}`);
                return pointer;
            }
        }
        return null; // 未找到8F标记
    } catch (error) {
        console.error('解析8F指针时出错:', error);
        return null;
    }
}

// 传入一个设备hid device 对象,进行open , 发送sendFeatureReport，返回匹配的deviceItem
export async function ryWiredSendFeatureReport(device, JsonItem) {
    return new Promise(async (resolve, reject) => {
        try {
            // 如果设备未打开，先打开它
            if (!device.opened) {
                await device.open();
            }
            
            const data = new Uint8Array(64);
            data[0] = 0x8f;
            data[7] = 0x70;
            await device.sendFeatureReport(0, data);
            
            // 使用 Promise 替代 setTimeout
            setTimeout(async () => {
                try {
                    const receivedData = await device.receiveFeatureReport(0);
                    console.log('receivedData===:', receivedData);
                    
                    // 解析数据，查找8F后一位的32-bit指针
                    const pointer32bit = parse8FPointer(receivedData);
                    if (pointer32bit !== null) {
                        const deviceId = `0x${pointer32bit.toString(16).toUpperCase()}`;
                        console.log('真实设备ID:', deviceId);
                        const deviceItem = JsonItem?.deviceIds?.find(i => i.id == deviceId);
                        
                        if (deviceItem) {
                            resolve(deviceItem);
                        } else {
                            resolve(null); // 找到指针但没有匹配的设备项
                        }
                    } else {
                        console.log('未找到8F标记');
                        resolve(null);
                    }
                } catch (error) {
                    console.error('接收特性报告时出错:', error);
                    reject(error);
                }
            }, 20);
        } catch (error) {
            console.error('发送特性报告时出错:', error);
            reject(error);
        }
    });
}

// ry
export async function ry24SendFeatureReport(device, JsonItem) {
  return new Promise(async (resolve, reject) => {
      try {
          // 如果设备未打开，先打开它
          if (!device.opened) {
              await device.open();
          }
          
          const data1 = new Uint8Array(64); 
          data1[0] = 0xf7;
          console.log("data1===:", data1);
          await device.sendFeatureReport(0, data1);

          const data0 = new Uint8Array(64); data0[0] = 0xfe;data0[1] = 0x40
          console.log("data(fe40)===:", data0);
          await device.sendFeatureReport(0, data0);
          
          setTimeout(async () => {
              try {
                  const receivedData = await device.receiveFeatureReport(0);
                  console.log("f7===:", receivedData);
                  
                  // receivedData已经是DataView对象，直接使用
                  // 判断第4位不是0且第5位是0
                  if (receivedData.getUint8(3) != 0 && receivedData.getUint8(4) == 0) {
                      console.log("条件匹配: 第4位不是0且第5位是0");
                      console.log(`第4位值: ${receivedData.getUint8(3)}, 第5位值: ${receivedData.getUint8(4)}`);
                      
                      const data2 = new Uint8Array(64); 
                      data2[0] = 0xf6;
                      data2[1] = 0x0a;
                      console.log("data2===:", data2);
                      await device.sendFeatureReport(0, data2);
                      
                      setTimeout(async () => {
                          const data3 = new Uint8Array(64); 
                          data3[0] = 0x8f;
                          data3[7] = 0x70;
                          console.log("data3===:", data3);
                          await device.sendFeatureReport(0, data3);
                          
                          setTimeout(async () => {
                              const data4 = new Uint8Array(64); 
                              data4[0] = 0xfc;
                              console.log("data4===:", data4);
                              await device.sendFeatureReport(0, data4);
                              
                              setTimeout(async () => {
                                  try {
                                      const finalReceivedData = await device.receiveFeatureReport(0);
                                      console.log("res===:", finalReceivedData);
                                      
                                      // 解析数据，查找8F后一位的32-bit指针
                                      const pointer32bit = parse8FPointer(finalReceivedData);
                                      if (pointer32bit !== null) {
                                          const deviceId = `0x${pointer32bit.toString(16).toUpperCase()}`;
                                          console.log('真实设备ID:', deviceId);
                                          const deviceItem = JsonItem?.deviceIds?.find(i => i.id == deviceId);
                                          
                                          if (deviceItem) {
                                              resolve(deviceItem);
                                          } else {
                                              resolve(null); // 找到指针但没有匹配的设备项
                                          }
                                      } else {
                                          console.log('未找到8F标记');
                                          resolve(null);
                                      }
                                  } catch (error) {
                                      console.error('接收最终特性报告时出错:', error);
                                      reject(error);
                                  }
                              }, 100);
                          }, 100);
                      }, 100);
                  } else {
                      console.log("条件不匹配");
                      console.log(`第4位值: ${receivedData.getUint8(3)}, 第5位值: ${receivedData.getUint8(4)}`);
                      resolve(null);
                  }
              } catch (error) {
                  console.error('接收特性报告时出错:', error);
                  reject(error);
              }
          }, 100);
      } catch (error) {
          console.error('发送特性报告时出错:', error);
          reject(error);
      }
  });
}

